package com.calvin.study.multithread.safe.pc.nosafe;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.calvin.study.multithread.safe.pc.Consumer;
import com.calvin.study.multithread.safe.pc.Goods;
import com.calvin.study.multithread.safe.pc.IGoods;
import com.calvin.study.multithread.safe.pc.Producer;

public class NotSafePetStore {

	// 数据缓冲区静态实例
	private static NotSafeDataBuffer<IGoods> notSafeDataBuffer = new NotSafeDataBuffer();
	// 生产者执行的动作
	static Callable<IGoods> produceAction = () -> {
		// 首先生成一个随机的商品
		IGoods goods = Goods.produceOne();
		// 将商品加上共享数据区
		try {
			notSafeDataBuffer.add(goods);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return goods;
	};
	// 消费者执行的动作
	static Callable<IGoods> consumerAction = () -> {
		// 从PetStore获取商品
		IGoods goods = null;
		try {
			goods = notSafeDataBuffer.fetch();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return goods;
	};

	public static void main(String[] args) {
		System.setErr(System.out);
		final int THREAD_TOTAL = 20;
		ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_TOTAL);

		for (int i = 0; i < 5; i++) {
			// 生产者实例每生产一个商品， 间隔500毫秒
			threadPool.submit(new Producer(produceAction, 500));
			// 消费者实例每消费一个商品， 间隔1500毫秒
			threadPool.submit(new Consumer(consumerAction, 1500));
		}
	}

}
